package com.tanhua.dubbo.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.api.UserLocationApi;
import com.tanhua.dubbo.pojo.UserLocation;
import com.tanhua.dubbo.vo.UserLocationVo;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@Service(version = "1.0.0")
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 更新用户地理位置
     *
     * @param userId    用户id
     * @param longitude 经度
     * @param latitude  纬度
     * @param address   地址
     * @return id
     */
    @Override
    public String updateUserLocation(Long userId, Double longitude, Double latitude, String address) {
        UserLocation userLocation = new UserLocation();
        userLocation.setAddress(address);
        userLocation.setUserId(userId);
        userLocation.setLocation(new GeoJsonPoint(longitude,latitude));

        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation ul = this.mongoTemplate.findOne(query,UserLocation.class);
        if (null == ul){
            userLocation.setId(ObjectId.get());
            userLocation.setCreated(System.currentTimeMillis());
            userLocation.setUpdated(userLocation.getCreated());
            userLocation.setLastUpdated(userLocation.getCreated());

            this.mongoTemplate.save(userLocation);
            return userLocation.getId().toHexString();
        } else {
            // 更新
            Update update=Update
                    .update("location",userLocation.getLocation())
                    .set("updated",System.currentTimeMillis())
                    .set("lastUpdated",ul.getUpdated())
                    .set("address",userLocation.getAddress());
            this.mongoTemplate.updateFirst(query,update,UserLocation.class);
        }

        return ul.getId().toHexString();
    }

    @Override
    public UserLocationVo queryByUserId(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserLocation userLocation = this.mongoTemplate.findOne(query, UserLocation.class);
        if (userLocation!= null){
            return UserLocationVo.format(userLocation);
        }
        return null;
    }

    @Override
    public List<UserLocationVo> queryUserFromLocation(Double longitude, Double latitude, Integer range) {
        // 中心点
        GeoJsonPoint geoJsonPoint = new GeoJsonPoint(longitude,latitude);
        // 转换为2dsphere的距离
        Distance distance = new Distance(Double.valueOf(range)/1000, Metrics.KILOMETERS);
        // 画一个圆
        Circle circle = new Circle(geoJsonPoint,distance);

        Query query = Query.query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocationList = this.mongoTemplate.find(query, UserLocation.class);
        return UserLocationVo.formatToList(userLocationList);
    }
}
